package com.imooc.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.imooc.resource.FileResource;
import com.imooc.service.FdfsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class FdfsServiceImpl implements FdfsService {

    // 通过Fdfs客户端来实现上传操作
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FileResource fileResource;

    /**
     *
     * @param file 文件
     * @param fileExtName 文件后缀名
     * @return 存储地址
     * @throws Exception
     */
    @Override
    public String upload(MultipartFile file, String fileExtName) throws Exception {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),
                                                                file.getSize(),
                                                                fileExtName,
                                                        null);
        // 通过 StorePath获取到相应的内容
        String path = storePath.getFullPath();
        return path;
    }

    @Override
    public String uploadOSS(MultipartFile file, String userId,String fileExtName) throws Exception {

        String endpoint = fileResource.getEndpoint();
        String accessKeyId = fileResource.getAccessKeyId();
        String accessKeySecret = fileResource.getAccessKeySecret();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().
                        build(endpoint, accessKeyId, accessKeySecret);

        // 获取输入流
        InputStream inputStream = file.getInputStream();

        String bucketName = fileResource.getBucketName();
        // 文件上传路径
        String objectName = fileResource.getObjectName() + "/"
                + userId + "/" + userId+"."+ fileExtName;
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(bucketName, objectName, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        // 文件上传的路径地址
        return  objectName;
    }
}
